package com.itheima.controller;

import com.github.pagehelper.PageInfo;
import com.itheima.domain.User;
import com.itheima.exception.BusinessException;
import com.itheima.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Description:
 * @Version: V1.0
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;


    @PostMapping
    public Result save(User user) {
        boolean flag = userService.save(user);
        return new Result(flag ? Code.SAVE_OK : Code.SAVE_ERR);
    }

    @PutMapping
    public Result update(User user) {
        boolean flag = userService.update(user);
        return new Result(flag ? Code.UPDATE_OK : Code.UPDATE_ERR);
    }

    @DeleteMapping("/{uuid}")
    public Result delete(@PathVariable("uuid") Integer uuid) {
        boolean flag = userService.delete(uuid);
        return new Result(flag ? Code.DELETE_OK : Code.DELETE_ERR);
    }

    @RequestMapping("/{uuid}")
    public Result get(@PathVariable Integer uuid) {
        User user = userService.get(uuid);
        if(uuid==10)throw new BusinessException("查询出错了,请重试!",Code.GET_ERR);
        return new Result(null!=user?Code.GET_OK:Code.GET_ERR,user);
    }

    @RequestMapping("/{page}/{size}")
    public Result getAll(@PathVariable("page") Integer page,
                         @PathVariable("size") Integer size) {
        PageInfo<User> all = userService.getAll(page, size);
        return new Result(null!=all?Code.GET_OK:Code.GET_ERR,all);
    }

    @PostMapping("/login")
    public Result login(String userName, String password) {
        User user = userService.login(userName, password);
        return new Result(null!=user?Code.GET_OK:Code.GET_ERR,user);
    }
}
